package com.qclix.inv.xml;

import com.qclix.inv.Invoice;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Translates objects to and from XML
 */
public class SpringXMLTranslator implements XMLTranslator {
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;
    private XMLtoDomainTranslator xmlToDomainTranslator;
    private DomainToXMLTranslator domainToXMLTranslator;

    public void setXmlToDomainTranslator(XMLtoDomainTranslator xmlToDomainTranslator) {
        this.xmlToDomainTranslator = xmlToDomainTranslator;
    }

    public void setDomainToXMLTranslator(DomainToXMLTranslator domainToXMLTranslator) {
        this.domainToXMLTranslator = domainToXMLTranslator;
    }

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }

    public String toXML(Invoice invoice) throws XMLTranslationException {
        try {
            StringWriter writer = new StringWriter();
            marshaller.marshal(domainToXMLTranslator.getXMLversion(invoice), new StreamResult(writer));
            return writer.toString();
        } catch (IOException e) {
            throw new XMLTranslationException(e);
        }
    }

    public Invoice fromXml(String xml) throws XMLTranslationException {
        try {
            return xmlToDomainTranslator.getDomainVersion((XMLInvoice) unmarshaller.unmarshal(new StreamSource(new StringReader(xml))));
        } catch (IOException e) {
            throw new XMLTranslationException(e);
        }
    }
}
